﻿using Consul;
using Microsoft.Extensions.Configuration;
using System.Net;

namespace ConsulUility
{
    public static class ConsulRegist
    {
        /// <summary>
        /// 健康检查
        /// </summary>
        /// <param name="configuration">扩展方法(读取配置文件的端口)</param>
        public static void ConsulExtend(this IConfiguration configuration)
        {
            //实例化Consul 客户端，配置要访问的Consul 地址
            ConsulClient client = new ConsulClient(c =>
            {
                //地址
                c.Address = new Uri(configuration["Consul:ConsulClient"]);
                //Datacenter 名称
                c.Datacenter = "dc1";
            });
            //var IPAddress = configuration["Consul:ServiceAddress"];
            //动态获取IP
            var IPAddress = GetHostIpForFas();
            int Port = 0;
            //获取端口
            int.TryParse(configuration["Consul:ServicePort"], out Port);
            //心跳检测
            var HealthUrl = configuration["Consul:HealthUrl"];

            //注册
            client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                //唯一标识
                ID = Guid.NewGuid().ToString(),
                //服务名称
                Name = configuration["Consul:ServiceName"],
                Address = IPAddress, //本机IP
                Port = Port,
                //健康检查(心跳检测)
                Check = new AgentServiceCheck()
                {
                    Interval = TimeSpan.FromSeconds(12),//间隔12s一次 检查
                    HTTP = $"http://{IPAddress}:{Port}{HealthUrl}", //访问API地址
                    Timeout = TimeSpan.FromSeconds(6), //等待检测时间
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20) //失败移除时间
                }
            }); ;
        }
        /// <summary>
        /// 获取用于 FAS 的主机 IP 地址
        /// </summary>
        /// <returns>主机 IP 地址字符串</returns>
        private static string GetHostIpForFas()
        {
            try
            {
                return System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString();
            }
            catch (Exception)
            {
                return string.Empty;
            }


        }
    }
}
